﻿using System;
using System.Collections.Generic;
using System.Linq;
using YJKSparseDisOfDoor.ModelLayer;
using YJKGeometryFuncs;

namespace YJKSparseDisOfDoor
{
	internal class DoorDistanceMatrix
	{
		internal void AddValue(RoomDoor inputStartDoor, RoomDoor inputEndDoor, double inputDistance)
		{
			if (!this.DicMatrix.ContainsKey(inputStartDoor))
			{
				this.DicMatrix.Add(inputStartDoor, new Dictionary<RoomDoor, KeyValuePair<RoomDoor, double>>());
			}
			if (this.DicMatrix[inputStartDoor] == null)
			{
				this.DicMatrix[inputStartDoor] = new Dictionary<RoomDoor, KeyValuePair<RoomDoor, double>>();
			}
			Dictionary<RoomDoor, KeyValuePair<RoomDoor, double>> dictionary = this.DicMatrix[inputStartDoor];
			if (!dictionary.ContainsKey(inputEndDoor))
			{
				dictionary.Add(inputEndDoor, new KeyValuePair<RoomDoor, double>(inputStartDoor, inputDistance));
				return;
			}
			if (dictionary[inputEndDoor].Value > inputDistance)
			{
				dictionary[inputEndDoor] = new KeyValuePair<RoomDoor, double>(inputStartDoor, inputDistance);
			}
		}

		internal void Update()
		{
			bool flag = false;
			for (int i = 0; i < this.DicMatrix.Keys.Count; i++)
			{
				try
				{
					RoomDoor key = this.DicMatrix.Keys.ElementAt(i);
					Dictionary<RoomDoor, KeyValuePair<RoomDoor, double>> dictionary = this.DicMatrix[key];
					do
					{
						flag = false;
						for (int j = 0; j < dictionary.Keys.Count; j++)
						{
							RoomDoor key2 = dictionary.ElementAt(j).Key;
							if (Geometry.LessThan(dictionary.ElementAt(j).Value.Value, 0.01))
							{
								RoomDoor key3 = key2;
								if (this.DicMatrix.ContainsKey(key3))
								{
									foreach (KeyValuePair<RoomDoor, KeyValuePair<RoomDoor, double>> keyValuePair in this.DicMatrix[key3])
									{
										if (dictionary.ContainsKey(keyValuePair.Key) && dictionary[keyValuePair.Key].Value > keyValuePair.Value.Value)
										{
											dictionary[keyValuePair.Key] = keyValuePair.Value;
											flag = true;
										}
									}
								}
							}
						}
					}
					while (flag);
				}
				catch (Exception)
				{
					throw;
				}
			}
		}

		public Dictionary<RoomDoor, Dictionary<RoomDoor, KeyValuePair<RoomDoor, double>>> DicMatrix = new Dictionary<RoomDoor, Dictionary<RoomDoor, KeyValuePair<RoomDoor, double>>>();
	}
}
